package cn.com.bonc.khjy.utils;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author BTW
 */
public class FileUtil {

    private final static Log log = LogFactory.get();

    public static boolean existFile( String filePath ) {
        return Files.exists( Paths.get( filePath ) );
    }

    public static int getFileLineCount( File file ) {
        try ( FileReader fileReader = new FileReader( file );
              LineNumberReader lineNumberReader = new LineNumberReader( fileReader ) ) {
            long fileLength = file.length();
            lineNumberReader.skip( fileLength );
            int lineCount = lineNumberReader.getLineNumber();
            return lineCount;
        } catch ( IOException e ) {
            log.error( e, SystemMessageId.CMP0000, e.getMessage() );
            return 0;
        }
    }

    public static boolean createFile( String filePath ) {
        try {
            if ( !Files.exists( Paths.get( filePath ) ) ) {
                String path = filePath.substring( 0, filePath.lastIndexOf( File.separator ) );
                if ( !Files.isReadable( Paths.get( path ) ) ) {
                    Files.createDirectories( Paths.get( path ) );
                }
                Files.createFile( Paths.get( filePath ) );
            }
            return true;
        } catch ( IOException e ) {
            log.error( e, SystemMessageId.CMP0000, e.getMessage() );
            return false;
        }
    }

    public static void saveFile( String input, File file ) {
        try ( FileWriter fileWriter = new FileWriter( file, true );
              PrintWriter printWriter = new PrintWriter( fileWriter ) ) {
            printWriter.println( input );
        } catch ( IOException e ) {
            log.error( e, SystemMessageId.CMP0000, e.getMessage() );
        }
    }

    public static boolean moveFile( String targetDirectory, String filePath ) {
        try{
            log.debug("临时文件:,{}",filePath);
            log.info("移动至目录,{}",targetDirectory);
            File file = new File( filePath );
            String fileName = filePath.substring( filePath.lastIndexOf( File.separator ), filePath.length() );
            if ( !Files.isReadable( Paths.get( targetDirectory ) ) ) {
                Files.createDirectories( Paths.get( targetDirectory ) );
            }
            String newFileName = fileName.replace( ".temp", ".txt");
            boolean boo=file.renameTo( new File(Paths.get( targetDirectory, newFileName).toString()) );
            log.info("文件移动状态:{}",boo);
            return boo;
        } catch ( IOException e ) {
            log.error( e, SystemMessageId.CMP0000, e.getMessage() );
            return false;
        }
    }

}
